package red.stu.pconstraint.xml;

import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import red.stu.pconstraint.io.Resources;

import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;

/**
 * XMLConfigResolver
 * @author yihrmc @stu.red
 * @date 2019/11/14 11:11
 */
public class XMLConfigResolver implements EntityResolver {

    private static final String PCONSTRAINT_CONFIG_SYSTEM = "pconstraint-config.dtd";

    private static final String PCONSTRAINT_CONFIG_DTD = "red/stu/pconstraint/builder/xml/pconstraint-config.dtd";


    public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
        try {
            if (systemId != null) {
                String lowerCaseSystemId = systemId.toLowerCase(Locale.ENGLISH);
                if (lowerCaseSystemId.contains(PCONSTRAINT_CONFIG_SYSTEM)) {
                    return getInputSource(PCONSTRAINT_CONFIG_DTD, publicId, systemId);
                }
            }
        } catch (Exception e) {
            throw new SAXException(e.toString());
        }
        return null;
    }

    private InputSource getInputSource(String path, String publicId, String systemId) {
        InputSource source = null;
        if (path != null) {
            try {
                InputStream in = Resources.getResourceAsStream(path);
                source = new InputSource(in);
                source.setPublicId(publicId);
                source.setSystemId(systemId);
            } catch (IOException e) {
                // ignore, null is ok
            }
        }
        return source;
    }

}
